package com.hanter.downloader.slice;

import com.hanter.downloader.Partial;

import java.util.ArrayList;
import java.util.List;

/**
 * min 8k bytes
 */
public class PartialMbSlicer implements PartialSlicer {

    public static final int MB = 1024 * 1024;

    public static final int MIN_BLOCK_SIZE = MB;

    public static final int MIN_PARTIAL_SIZE = MB;

    @Override
    public List<Partial> slice(final long fileSize) {
        int num;
        if (fileSize > 200 * 1024 * 1024) {
            num = 8;
        } else if (fileSize > 20 * 1024 * 1024) {
            num = 6;
        } else if (fileSize > 5 * 1024 * 1024) {
            num = 4;
        } else if (fileSize > MIN_PARTIAL_SIZE) {
            num = 2;
        } else {
            num = 1;
        }
        // 块对齐, MB 单位
        long blockSize = (fileSize / MIN_BLOCK_SIZE / num) * MIN_BLOCK_SIZE;
        final List<Partial> list = new ArrayList<>();
        long offset = 0;
        while (offset < fileSize) {
            long end = offset + blockSize;
            if (end > fileSize) {
                end = fileSize;
            }
            list.add(new Partial(offset, end - 1));
            offset = end;
        }
        return list;
    }

}
